import React, { useState, useEffect } from "react";
import { Form, Input, Button, Switch, message } from "antd";
import axios from "axios";

const Settings = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const fetchSettings = async () => {
    setLoading(true);
    try {
      const response = await axios.get("http://localhost:5000/api/settings");
      form.setFieldsValue(response.data);
    } catch (error) {
      console.error("Error fetching settings:", error);
      message.error("获取设置失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSettings();
  }, []);

  const handleSave = async (values) => {
    try {
      await axios.post("http://localhost:5000/api/settings", values);
      message.success("设置保存成功");
    } catch (error) {
      console.error("Error saving settings:", error);
      message.error("保存设置失败");
    }
  };

  return (
    <div style={{ padding: "24px" }}>
      <Form form={form} onFinish={handleSave} layout="vertical">
        <Form.Item name="api_key" label="OpenAI API 密钥">
          <Input.Password placeholder="请输入 API 密钥" />
        </Form.Item>
        <Form.Item name="notifications_enabled" label="启用实时通知" valuePropName="checked">
          <Switch />
        </Form.Item>
        <Button type="primary" htmlType="submit" loading={loading}>
          保存设置
        </Button>
      </Form>
    </div>
  );
};

export default Settings;